package com.example.servlet;

import com.example.model.FormData;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebServlet("/process-form")
public class FormProcessServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置请求和响应的字符编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 创建FormData对象
        FormData formData = new FormData();

        // 获取表单数据
        formData.setName(request.getParameter("name"));
        formData.setEmail(request.getParameter("email"));
        formData.setPhone(request.getParameter("phone"));
        formData.setGender(request.getParameter("gender"));

        // 处理爱好（多选框）
        String[] hobbiesArray = request.getParameterValues("hobbies");
        if (hobbiesArray != null) {
            List<String> hobbies = Arrays.asList(hobbiesArray);
            formData.setHobbies(hobbies);
        }

        formData.setAddress(request.getParameter("address"));
        formData.setMessage(request.getParameter("message"));

        // 将数据存储在session中
        HttpSession session = request.getSession();
        session.setAttribute("formData", formData);

        // 重定向到数据查看页面
        response.sendRedirect("form-data.jsp");
    }
}